import express from "express";
import { spawn } from "child_process";
import path from "path";

const app = express();
const port = 3000;
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

let urlArr = new URL(".", import.meta.url).pathname.split("/");
const __dirname = urlArr.filter((o) => !!o).join("/");

app.get("/nodeTestGet", (req, res) => {
  res.send({
    success: true,
    result: req.query,
  });
});

app.post("/nodeTestPost", (req, res) => {
  res.send({
    success: true,
    result: req.body,
  });
});

app.get("/py/script", async (req, res) => {
  const pythonProcess = await spawn("python", [
    path.resolve(__dirname, "../python/test.py"), // python执行脚本路径
    "getFunc", // python脚本中的函数名
    JSON.stringify(req.query), // 需要传入的参数，因为是数组，保持一致性
  ]);
  try {
    pythonProcess.stdout.on("data", (data) => {
      res.send({
        success: true,
        result: data.toString(),
      });
    });
  } catch (error) {
    pythonProcess.stderr.on("data", (data) => {
      res.status(500).send(data.toString());
    });
  }
});

app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});
